//
//  JYHomeViewController.swift
//  WeiBoDemo
//
//  Created by 万佳阳 on 16/8/1.
//  Copyright © 2016年 JYWan. All rights reserved.
//

import UIKit
import SDWebImage
import MJRefresh

class JYHomeViewController: JYBaseViewController {
   
    
    // MARK:- 懒加载属性
    private lazy var titleBtn : JYTitleButton = JYTitleButton()
    private lazy var popoverAnimation : JYPopoverAnimation = JYPopoverAnimation {[weak self] (presented) in
        self?.titleBtn.selected = presented
    }
    private lazy var viewModels : [JYStatusViewModel] = [JYStatusViewModel]()
    private lazy var tipLabel : UILabel = UILabel()
    private lazy var photoBrowserAnimation : JYPhotoBrowserAnimation = JYPhotoBrowserAnimation()
    
    // MARK:- 系统回调函数
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //没有登录时设置的内容
        visitorView.addRotationAnimation()
        if !isLogin {
            return
        }
        
        //设置导航栏的内容
        setupNavigationbar()
        
        //设置刷新控件
        setupRefresh()
        
        //设置顶部提示label
        setupTipLabel()
        
        //估算高度
        tableView.estimatedRowHeight = 200
        
        //监听通知
        setupNotification()
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}

// MARK:- 设置UI界面
extension JYHomeViewController {
    private func setupNavigationbar() {
        //设置左侧item
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendattention")
        
        //设置右侧item
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop")
        
        //设置标题item
        titleBtn .setTitle("诗妹子", forState: .Normal)
        titleBtn.addTarget(self, action: #selector(JYHomeViewController.titleBtnClick(_:)), forControlEvents: .TouchUpInside)
        navigationItem.titleView = titleBtn
        
    }
  
    private func setupRefresh() {
        //header
        tableView.mj_header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(JYHomeViewController.loadNewData))
        tableView.mj_header.beginRefreshing()
        
        //footer
        tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: #selector(JYHomeViewController.loadMoreData))
    }
    
    private func setupTipLabel() {
        navigationController?.navigationBar.insertSubview(tipLabel, atIndex: 0)
        
        tipLabel.frame = CGRect(x: 0, y: 10, width: UIScreen.mainScreen().bounds.width, height: 32)
        
        tipLabel.backgroundColor = UIColor.orangeColor()
        tipLabel.textColor = UIColor.whiteColor()
        tipLabel.font = UIFont.systemFontOfSize(14)
        tipLabel.textAlignment = .Center
        tipLabel.hidden = true
    }
    
    private func setupNotification() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(JYHomeViewController.showPhotoBrowser(_:)), name: showPhotoBrowserNote, object: nil)
    }
}

// MARK:- 事件监听
extension JYHomeViewController {
    @objc private func titleBtnClick(titleBtn : JYTitleButton) {
        //改变按钮状态
        titleBtn.selected = !titleBtn.selected;
        
        //弹出控制器
        let popoverVc = JYPopoverViewController()
        
        //设置控制器modal样式
        popoverVc.modalPresentationStyle = .Custom
        
        //设置转场代理
        popoverVc.transitioningDelegate = popoverAnimation
        popoverAnimation.presentedFrame = CGRect(x: 120, y: 55, width: 180, height: 250)
        
        presentViewController(popoverVc, animated: true, completion: nil)
        
    }
    
    @objc private func showPhotoBrowser(note : NSNotification) {
        //取出数据
        guard let indexPath = note.userInfo![showPhotoBrowserIndexKey] as? NSIndexPath else {
            return
        }
        
        guard let picURLs = note.userInfo![showPhotoBrowserPicURLsKey] as? [NSURL] else {
            return
        }
        let picCollectionView = note.object as! JYPicCollectionView
        
        //创建控制器
        let photoBrwoserVc = JYPhotoBrowserViewController(indexPath: indexPath, picURLs: picURLs)
        
        //设置modal样式
        photoBrwoserVc.modalPresentationStyle = .Custom
        
        //设置转场代理
        photoBrwoserVc.transitioningDelegate = photoBrowserAnimation
        
        photoBrowserAnimation.presentedDelegate = picCollectionView
        photoBrowserAnimation.indexPath = indexPath
        
        //弹出控制器
        presentViewController(photoBrwoserVc, animated: true, completion: nil)
    }
}

// MARK:- 请求数据
extension JYHomeViewController {
    //加载新数据
    @objc private func loadNewData() {
        loadStatuses(true)
    }
    
    //加载更多数据
    @objc private func loadMoreData() {
        loadStatuses(false)
    }
    
    private func loadStatuses(isNewData : Bool) {
        //获取since_id/max_id
        var since_id = 0
        var max_id = 0
        
        if isNewData {
            since_id = viewModels.first?.status?.mid ?? 0
        } else {
            max_id = viewModels.last?.status?.mid ?? 0
            max_id = max_id == 0 ? 0 : (max_id - 1)
        }
        
        //请求数据
        NetworkTools.shareInstance.loadStatuses(since_id, max_id: max_id) { (result, error) in
            //错误校验
            if error != nil {
                print(error)
                return
            }
            
            //获取可选类型中的数据
            guard let resultArray = result else {
                return
            }
            
            //字典转模型
            var tempViewModels = [JYStatusViewModel]()
            for statusDict in resultArray {
                let status = JYStatus(dict: statusDict)
                let viewModel = JYStatusViewModel(status: status)
                tempViewModels.append(viewModel)
            }
            
            //将数据放到成员变量的数组中
            if isNewData {
                self.viewModels = tempViewModels + self.viewModels
            } else {
                self.viewModels += tempViewModels
            }
            
            //缓存图片
            self.cacheImage(tempViewModels)
        }
    }
    
    private func cacheImage(viewModels : [JYStatusViewModel]) {
        //创建group
        let group = dispatch_group_create()
        
        //缓存图片
        for viewModel in viewModels {
            for picURL in viewModel.picURLs {
                dispatch_group_enter(group)
                SDWebImageManager.sharedManager().downloadImageWithURL(picURL, options: [], progress: nil, completed: { (_, _, _, _, _) in
                    dispatch_group_leave(group)
                })
            }
        }
        
        //刷新表格
        dispatch_group_notify(group, dispatch_get_main_queue()) { 
            self.tableView.reloadData()
            
            //结束刷新
            self.tableView.mj_header.endRefreshing()
            self.tableView.mj_footer.endRefreshing()
            
            //显示提示label
            self.showTipLabel(viewModels.count)
        }
    }
    
    ///显示提示label
    private func showTipLabel(count : Int) {
        tipLabel.text = count == 0 ? "没有新微博" : "\(count)条新微博"
        tipLabel.hidden = false
        
        //执行动画
        UIView .animateWithDuration(0.5, animations: {
            self.tipLabel.frame.origin.y = 44
            }) { (_) in
                UIView.animateWithDuration(0.5, delay: 1.5, options: [], animations: {
                    self.tipLabel.frame.origin.y = 10
                    }, completion: { (_) in
                        self.tipLabel.hidden = true
                })
        }
    }
}

// MARK:- tableView数据源方法
extension JYHomeViewController {
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        tableView.mj_footer.hidden = (viewModels.count == 0)
        return viewModels.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("status") as! JYHomeViewCell
        
        cell.viewModel = viewModels[indexPath.row]
        
        return cell
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        //取出模型
        let viewModel = viewModels[indexPath.row]
        
        return viewModel.cellHeight
        
    }
}
